#include "SudokuHiddenSubsets.h"

SudokuHiddenSubsets::SudokuHiddenSubsets(QObject* parent) :
        SudokuAbstractSolvingTechnique("Hidden Subsets", HiddenSubsets, EliminateCandidate, parent)
{
}

int SudokuHiddenSubsets::solve()
{
    for(int houseInd=0; houseInd<mSudokuData->getSize(); ++houseInd)
    {
        findHiddenSubsetsInHouse(mSudokuData->houseAtRow(houseInd));
        findHiddenSubsetsInHouse(mSudokuData->houseAtCol(houseInd));
        findHiddenSubsetsInHouse(mSudokuData->houseAtBox(houseInd));
    }

    qDebug() << "SudokuHiddenSubsets::solve: " << mCount;
    return mCount;
}


void SudokuHiddenSubsets::findHiddenSubsetsInHouse(SudokuHouse* house)
{
    //TODO run only for small groups?
    QList< QPair<int,int> > candidateCount = house->getCandidateListByCount();

    int baseIndex = candidateCount.size()-1;

    while(baseIndex>0 && candidateCount.at(baseIndex).first>=2)
    {
        QList<int> candidateList;
        candidateList.append(candidateCount.at(baseIndex).second);
        SudokuCellSet baseGroup = house->getCellsWithCandidate(candidateCount.at(baseIndex).second);
        --baseIndex;
        int currentIndex = baseIndex;
        while(currentIndex>=0 && candidateCount.at(currentIndex).first>=0)
        {
            SudokuCellSet currentGroup = house->getCellsWithCandidate(candidateCount.at(currentIndex).second);
            if(baseGroup.containsSet(currentGroup)) //TODO nie dolacza malych grup, 6 i 4 z przykladu
                candidateList.append(candidateCount.at(currentIndex).second);//candidate found
            --currentIndex;
        }
        qDebug() << "baseGroup.size(): " << baseGroup.size() << "candidateList.size(): " << candidateList.size();
        if(baseGroup.size() == candidateList.size())
        {
            //group found
            qDebug() << "GROUP FOUND !!!!!!!!!!!!!!!!!!";
            QList<int> cellIndexList;
            foreach(SudokuCell* cell, baseGroup)
                cellIndexList.append(cell->getIndex());
            mCount += house->eliminateAllOthers(cellIndexList, candidateList, HiddenSubsets);
        }

    }
}

